import api from '@/odoorpc'

export default {
  components: {},
  mixins: [],
  props: {
    actionId: { type: String, default: undefined }
  },

  data() {
    return {
      treeview: undefined, // 对象, 接口函数的入口

      fields: {},
      records: [],
      activeIds: [],

      search_values: [],
      search_items: {}
    }
  },

  computed: {
    columns() {
      const get_render = (col, meta) => {
        if (meta.type === 'many2one') {
          // eslint-disable-next-line no-unused-vars
          return (value, row, index) => (value ? value[1] : '')
        } else if (meta.type === 'selection') {
          const get_label = value => {
            const elm = meta.selection.find(item => item[0] === value)
            return elm ? elm[1] : ''
          }
          // eslint-disable-next-line no-unused-vars
          return (value, row, index) => (value ? get_label(value) : '')
        } else if (meta.type === 'boolean') {
          // eslint-disable-next-line no-unused-vars
          return (value, row, index) => (value ? '是' : '否')
        } else {
          return undefined
        }
      }

      const fields = this.fields
      const cols = Object.keys(fields)
        .filter(item => !fields[item].invisible)
        .map(fld => {
          const meta = fields[fld]

          const col = { dataIndex: fld, key: fld, title: meta.string }

          const render = get_render(fld, meta)
          if (render) {
            col.customRender = render
          }

          return col
        })

      return cols
    },

    rowSelection() {
      return {
        selectedRowKeys: this.activeIds,
        onChange: (selectedRowKeys, selectedRows) => {
          // console.log(selectedRowKeys, selectedRows)
          this.activeIds = selectedRowKeys
          this.rowSelected()
          // this.handleOnRowSelect(selectedRowKeys, selectedRows)
        }
      }
    }
  },

  created() {},

  mounted() {},

  methods: {
    async rowSelected() {
      // to override
    },
    async search_data(activeIds) {
      const actionId = this.actionId
      console.log('activeIds', activeIds, actionId)
      const treeview = api.env.treeview(actionId)
      this.treeview = treeview

      console.log('treeview', treeview)
      // this.buttons = treeview.buttons
      // this.actionBtns = treeview.action_buttons
      this.fields = await treeview.load_fields()

      if (activeIds) {
        treeview.domain_local = [['id', 'in', activeIds]]
      }

      this.search_items = this.treeview.search_items

      this.init_filter()

      this.records = await treeview.search_read()
      await this.search_relation()
    },

    init_filter() {
      // to override
    },

    search_relation() {
      // to override
    }
  }
}
